"use strict";
const Command = require("@wenjun-cli/command");
const inquirer = require("inquirer");
const log = require("@wenjun-cli/log");
const path = require("path");
const fs = require("fs");
const { spinnerStart } = require("@wenjun-cli/utils");
const request = require("@wenjun-cli/request");

class AddUserCommands extends Command {
  init() {}
  async exec() {
    // 第一步：输入用户名以及密码
    const username = (
      await inquirer.prompt({
        type: "input",
        name: "username",
        message: "请输入用户名：",
      })
    ).username;
    const password = (
      await inquirer.prompt({
        type: "password",
        name: "password",
        message: "请输入密码：",
      })
    ).password;
    const passwordRepeat = (
      await inquirer.prompt({
        type: "password",
        name: "passwordRepeat",
        message: "请再次输入密码：",
      })
    ).passwordRepeat;
    // 第二步：校验两次输入的密码是否一致
    if (password !== passwordRepeat) {
      return log.error("两次输入的密码不一致，请重试！");
    }
    // 第三步：添加用户
    const spinner = spinnerStart("请求中.........");
    try {
      const res = await request.post(
        "/user/createUser",
        { username, password },
        {
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      spinner.stop(true);
      if (res.code === 0) {
        return log.success("添加成功！");
      }
      log.error(res.message);
    } catch (e) {
      spinner.stop(true);
      log.error("添加出错，稍后重试！");
    }
  }
}

function index(argv) {
  return new AddUserCommands(argv);
}

module.exports = index;
module.exports.AddUserCommands = AddUserCommands;
